﻿using NX5Web.Entities;
using CommHelper;
using JWT.Algorithms;
using JWT.Serializers;
using JWT;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Text;
using System.Web.Http;
using System.Runtime.Caching;
using NX5Web.Utils;
using NX5Web.Filters;
using System.Web.UI.WebControls;

namespace NX5Web.Controllers
{
  public class AccountController : BaseApiController
  {

    [HttpPost]
    public IHttpActionResult Login(LoginRequest loginRequest)
    {
      if (loginRequest == null)
      {
        return ReturnFail("登录信息为空!");
      }

      var defaultCache = MemoryCache.Default;
      var randomCache = defaultCache[loginRequest.UUID]; // 获取缓存项的值
      if (defaultCache == null || randomCache == null || randomCache.ToString() == "" || randomCache.ToString() != loginRequest.Code)
      {
        return ReturnFail("验证码输入有误!");
      }

      DataManager dm = new DataManager();
      DataToInfo accounts = dm.Procedure("Login", "[{'UserName':'" + loginRequest.UserName + "','PassWord':'" + loginRequest.PassWord + "'}]");
      if (accounts.table.Rows.Count == 0)
      {
        return ReturnFail("用户名或密码错误!");
      }

      // 移除指定的缓存项
      defaultCache.Remove(loginRequest.UUID);

      // 生成Token令牌
      var token = JwtHelper.GenerateToken(accounts.table.Rows[0]["ID"].ToString(), "admin", 60 * 24);

      //AuthInfo authInfo = new AuthInfo()
      //{
      //    ID = (int)accounts.Rows[0]["ID"],
      //    UserName = loginRequest.UserName,
      //    Expires = DateTime.Now.AddDays(30)
      //};

      // 移除账户登录缓存
      //if (defaultCache.Contains(token))
      //{
      //    defaultCache.Remove(token);
      //}

      // 添加一个新缓存项，设置过期时间为1天
      //defaultCache.Add(token, authInfo, DateTimeOffset.UtcNow.AddMinutes(60 * 24));

      return ReturnSuccess(new ApiHttpRequest
      {
        status = true,
        data = token,
        message = "登录成功!"
      });
    }

    [HttpPost]
    public IHttpActionResult GetUserInfo(CommonDate CD)
    {
      DataManager dm = new DataManager(new DataLog(Url.Request.RequestUri.ToString(), CD.OpUid));
      DataToList dataList;
      try
      {
        dataList = dm.ProcedureSet("GetUserInfo", "[{\"ID\":\"" + CD.OpUid + "\",\"OpUid\":\"" + CD.OpUid + "\"}]");
        dataList.tables[0].table.Columns.Remove("PassWord");
      }
      catch (Exception ex)
      {
        //String Parms = "{\"Name\":\"" + CD.Name + "\",\"Parameters\":\"" + CD.Parameters + "\",\"AuthCode\":\"" + CD.AuthCode + "\"}"; 
        ErrorHandle.SaveError(Url.Request.RequestUri.ToString(), "{\"Name\": \"" + "GetUserInfo" + "\",\"Parameters\":[{\"ID\":\"" + CD.OpUid + "\"},\"OpUid\":" + CD.OpUid + "\"]}", ex.Message);
        throw new Exception(ex.ToString());
      }

      return ReturnSuccess(dataList);
    }
  }
}
